<script>
import request from "@/utils/request"
import numberUtils from "@/utils/numberUtils"
import { assignObj, clearObj, getShowImage, showModal } from "@/utils"
import shareInfo from "@/utils/shareInfo"
import clockIcon from "./assets/clock.png"
import courseHoursIcon from "./assets/courseHours.png"
import userIcon from "./assets/user.png"
import footerContent from "./component/footerContent.vue"
import { getSysParam } from "@/utils"
import banner from "@/components/banner.vue"
import coupon from "@/components/coupon/index.vue"
import websocket from "@/utils/websocket"
import common from "./common"
import pay from "@/utils/pay"
import teamBuying from "@/components/teamBuying/teamBuying.vue"
import studyRoomFloat from "@/components/studyRoomFloat/index.vue"

export default {
  name: "detail",
  components: { teamBuying, footerContent, banner, coupon, studyRoomFloat },
  data() {
    return {
      details: null,
      clockIcon,
      courseHoursIcon,
      userIcon,
      exclusiveId: "", //专属下单码id
      openCoursePage: false,
      queryParams: {
        id: "",
      },
      numberUtils,
      sum: 0, //总价（使用了所有优惠之后的价格）
      couponDiscount: 0, //使用了优惠券之后的减免金额
      userCouponId: "", //优惠券id（用于提交订单的时候传参过去）
      openIosPay: false, //是否开启ios支付

      teamBuyingDetails: [], //拼团详情
      myTeamBuyingDetails: null, //我的拼团详情
      groupBuyId: "", //拼团id
      groupIdentification: "", //拼团标识
      shareUserGroupIdentification: "", //分享人的拼团标识
      shareUserGroupBuyId: "", //分享人的拼团id
      shareTeamBuyingPrice: "", //分享人的拼团价格
    }
  },
  onShow() {
    websocket.trackCurrentPage("课程详情").catch(() => {})
  },
  async onLoad(query) {
    // 读取页面参数里面的拼团参数
    this.shareUserGroupIdentification = query.shareUserGroupIdentification
    this.shareUserGroupBuyId = query.shareUserGroupBuyId
    this.shareTeamBuyingPrice = query.shareTeamBuyingPrice ? Number.parseInt(query.shareTeamBuyingPrice) : 0
    // ios 支付
    pay.checkIosPay().then((boolean) => {
      this.openIosPay = boolean
      if (!boolean) {
        showModal({
          title: "提示",
          content: "根据相关政策，ios不提供此服务",
          showCancel: false,
        })
      }
    })
    //检查是否有开启课程板块
    this.openCoursePage = (await getSysParam("openCoursePage")) !== "否"
    let id
    //通过扫码的方式进入
    if (query.scene) {
      const scene = decodeURIComponent(query.scene)
      function parseQueryString(query) {
        const params = {}
        // 将查询字符串按 & 分割成多个参数
        const pairs = query.split("&")
        // 遍历每个参数
        for (const pair of pairs) {
          // 将参数按 = 分割成键值对
          const [key, value] = pair.split("=")
          // 将解析出的键值对存储在 params 对象中
          params[key] = value
        }
        return params
      }
      let searchParams = parseQueryString(scene)
      id = searchParams.ID
      let code = searchParams.CODE
      this.exclusiveId = code
      //通过常规的方式传入
    } else {
      id = query.id
    }
    this.queryParams.id = id
    //获取课程详情
    await this.getDetails()
    //商品未下架，且还未购买过，且配置了开启拼团，获取拼团详情
    if (this.details.salesStatus !== 2 && this.details.isRegistered === 0 && this.details.enableTeamwork === 1) {
      this.$nextTick(() => {
        this.$refs.teamBuying.init()
      })
    }
  },
  methods: {
    getShowImage,
    getDetails() {
      return new Promise((resolve, reject) => {
        common.getDetails(this.queryParams.id).then((data) => {
          this.details = data
          this.sum = data.price
          this.$forceUpdate()
          //动态设置页面标题
          uni.setNavigationBarTitle({
            title: data.className,
          })
          resolve()
        })
      })
    },
    //处理使用了优惠券后的价格减免
    handlePriceReduction() {
      const result = this.details.price - this.couponDiscount
      //防止算出的价格小于0
      this.sum = result >= 0 ? result : 0
    },
  },
  //配置右上角分享
  async onShareAppMessage() {
    return await common.getShareInfo("", {
      shareUserGroupIdentification: this.groupIdentification,
      shareUserGroupBuyId: this.groupBuyId,
      shareTeamBuyingPrice: this.myTeamBuyingDetails ? this.myTeamBuyingDetails.commodityGroupBuy.price : "",
    })
  },
  provide() {
    return {
      parent: this,
    }
  },
}
</script>

<template>
  <view class="page" v-if="details && openCoursePage && openIosPay">
    <!--		课程详情轮播图-->
    <banner
      :banner-list-props="
        details.topCarouselList.map((item) => {
          return { imagePath: item }
        })
      "
      :show-indicator-dots="false"
      height="400rpx"
    ></banner>
    <view class="content">
      <view class="course-name">{{ details.className }}</view>
      <!--			只有未购买过、价格不为0时才展示价格-->
      <view class="price" v-if="details.isRegistered === 0 && details.price !== 0">
        <text style="font-size: 26rpx">￥</text>
        <text style="font-size: 36rpx">{{ numberUtils.fenToYuan(details.price) }}</text>
      </view>
      <!--			课时、有效期、报名人数-->
      <view class="info">
        <!--				课时不为0时才展示-->
        <view class="item" v-if="details.lessonHours !== '0'">
          <image :src="courseHoursIcon" class="icon"></image>
          {{ details.lessonHours + " " }}课时
        </view>
        <view class="item">
          <image :src="clockIcon" class="icon"></image>
          有效期至{{ " " + details.effectiveTime }}
        </view>
        <view class="item">
          <image :src="userIcon" class="icon"></image>
          {{ details.registeredNum + details.virtualRegisteredNum + " " }}人已报名
        </view>
      </view>
    </view>
    <!--		优惠券，之前没有买过才展示，免费课程不展示-->
    <template v-if="details && details.isRegistered === 0 && details.price !== 0">
      <view class="coupon-container">
        <coupon
          :origin-price="details.price"
          :coupon-type-list="[0, 3]"
          :couponDiscount.sync="couponDiscount"
          :userCouponId.sync="userCouponId"
          @change="handlePriceReduction"
        ></coupon>
      </view>
    </template>
    <!--		报名后加v二维码（仅购买过才提示）-->
    <template v-if="details.isRegistered === 1 && details.contactQrcode">
      <view class="divide-line"></view>
      <image :src="getShowImage(details.contactQrcode)" mode="widthFix" style="width: 100vw" :show-menu-by-longpress="true"></image>
    </template>
    <view class="divide-line"></view>
    <view class="detail" v-for="item in details.customList" :key="item.id">
      <view class="title">
        <view class="point"></view>
        {{ item.title }}
      </view>
      <image
        v-for="image in item.imagesContentList"
        :key="image"
        class="detail-image"
        mode="widthFix"
        :src="getShowImage(image)"
        :show-menu-by-longpress="true"
      ></image>
    </view>
    <!--		底部-->
    <footerContent
      @getDetails="getDetails"
      :details="details"
      :team-buying-details="teamBuyingDetails"
      :my-team-buying-details="myTeamBuyingDetails"
      :shareUserGroupIdentification="shareUserGroupIdentification"
      :shareTeamBuyingPrice="shareTeamBuyingPrice"
    ></footerContent>
    <!--		拼团购买-->
    <teamBuying
      ref="teamBuying"
      :commodity-icon="details.topCarouselList[0]"
      :commodity-name="details.className"
      :commodity-id="details.id"
      :commodity-type="1"
      :my-team-buying-details.sync="myTeamBuyingDetails"
      :team-buying-details.sync="teamBuyingDetails"
      :group-buy-id.sync="groupBuyId"
      :group-identification.sync="groupIdentification"
      :shareUserGroupIdentification.sync="shareUserGroupIdentification"
      :shareUserGroupBuyId.sync="shareUserGroupBuyId"
      @refreshDetail="getDetails"
    ></teamBuying>
    <studyRoomFloat></studyRoomFloat>
  </view>
</template>

<style scoped lang="scss">
.page {
  min-height: 100vh;
  .content {
    background: white;
    transform: translateY(-30rpx);
    border-radius: 30rpx 30rpx 0 0;
    padding: {
      top: 30rpx;
      left: 30rpx;
      right: 30rpx;
    }
    .course-name {
      font-size: 36rpx;
      font-weight: bold;
    }
    .price {
      margin-top: 30rpx;
      color: #de0000;
      font-weight: 600;
    }
    .info {
      display: flex;
      justify-content: space-between;
      font-size: 28rpx;
      color: var(--text-color-light);
      margin-top: 20rpx;
      .item {
        display: flex;
        align-items: center;
        .icon {
          width: 27rpx;
          height: 27rpx;
          margin-right: 8rpx;
        }
      }
    }
  }
  .divide-line {
    height: 20rpx;
    background: var(--gray-background-color);
  }
  .coupon-container {
    border: 3rpx solid var(--border-color);
    border-radius: 20rpx;
    margin: 20rpx;
  }
  .detail {
    .title {
      padding: 30rpx;
      display: flex;
      align-items: center;
      font-weight: bold;
      font-size: 32rpx;
      .point {
        display: inline-block;
        width: 8rpx;
        height: 28rpx;
        background: var(--theme-color);
        margin-right: 12rpx;
      }
    }
    .detail-image {
      width: 100vw;
    }
  }
}
</style>
